package org.shilong.UI.party;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

import org.shilong.ActionItem;
import org.shilong.QuickAction;
import org.shilong.MContext.Json.JSonContext;
import org.shilong.MContext.Party.PartyContext;
import org.shilong.MContext.WebRequest.WebRequestContext;
import org.shilong.MView.PullToRefreshListView;
import org.shilong.Model.PartyModel;
import org.shilong.UI.R;
import org.shilong.Utility.GenerateTime;
import org.shilong.Utility.PartyComparotr;
import org.shilong.Utility.ProgressDialogUtility;
import org.shilong.Utility.SharedPreferenceUtility;
import org.shilong.Utility.ToastUtility;
import org.shilong.ViewUtility.MyAnimationUtils;

import android.app.ActivityGroup;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PariesCreateByMeFrame extends ActivityGroup {

	private String[] arr;

	private LinearLayout layout_manager_paries_father_outter_layout;

	private PopupWindow myPopWindow;

	private PullToRefreshListView show_me_created_in_listview;

	private int centerX;
	private int centerY;

	/* 存放用户信息的list */
	public static LinkedList<PartyModel> pariesOfMineList = new LinkedList<PartyModel>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_paries_created_by_me_content);

		arr = SharedPreferenceUtility.getPersonInfoFromSharedPreference(this);

		initViews();

		registerEvents();

	}

	private void initViews() {
		// TODO Auto-generated method stub

		layout_manager_paries_father_outter_layout = (LinearLayout) this
				.findViewById(R.id.layout_manager_paries_father_outter_layout);

		show_me_created_in_listview = (PullToRefreshListView) this
				.findViewById(R.id.show_me_created_in_listview);

		show_me_created_in_listview.setAdapter(new MyAdapter(pariesOfMineList));

	}

	private void registerEvents() {

		show_me_created_in_listview
				.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

					@Override
					public void onRefresh() {
						// TODO Auto-generated method stub

						GetDatas task = new GetDatas();

						task.execute();
					}
				});

	}

	/**
	 * 获取数据task
	 * 
	 * @author cesc
	 * 
	 */
	private class GetDatas extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			String rlt = "nodatas";
/*
			rlt = (String) PartyContext.getInstance(
					PartyContext.QUERY_PARTIES_BY_ME).getRlt(arr[2]);
*/
			return rlt;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			System.out.println("新刷新我发起的聚会信息是:" + result);

			LinkedList<PartyModel> newll = new LinkedList<PartyModel>();

			newll = (LinkedList<PartyModel>) JSonContext.createInstance(
					JSonContext.TYPE_GET_PARIES_CREATED_BY_ME).getJsonRlt(
					result);

			addDatasToList(newll);

			show_me_created_in_listview.onRefreshComplete();

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			System.out.println("开始重新刷新我发起的聚会");
			super.onPreExecute();
		}

	}

	/**
	 * 想list中加入新的数据
	 * 
	 * @param newList
	 */
	private void addDatasToList(LinkedList<PartyModel> newList) {

		pariesOfMineList = new LinkedList<PartyModel>();

		Iterator<PartyModel> it = newList.iterator();

		while (it.hasNext()) {
			PartyModel partyModel = it.next();

			pariesOfMineList.addFirst(partyModel);

		}

		Collections.sort(pariesOfMineList, new PartyComparotr());

	}

	private class MyAdapter extends BaseAdapter {
		private LinkedList<PartyModel> mList;

		public MyAdapter(LinkedList<PartyModel> ll) {

			this.mList = ll;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub

			final int position = arg0;

			LayoutInflater inflater = (LayoutInflater) PariesCreateByMeFrame.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View root = inflater.inflate(R.layout.inner_listview_party_layout,
					null);

			LinearLayout layout = (LinearLayout)root.findViewById( R.id.inner_party_box_layout );
			
			if( arg0 % 2 != 0 ){
				layout.setBackgroundResource( R.drawable.msgbox_rec );
			}else{
				layout.setBackgroundResource( R.drawable.msgbox_send );
			}
			
			TextView title = (TextView) root
					.findViewById(R.id.party_listview_title_textview);
			TextView time = (TextView) root
					.findViewById(R.id.party_listview_time_textview);
			TextView content = (TextView) root
					.findViewById(R.id.party_listview_content_textview);

			PartyModel model = new PartyModel();

			model = mList.get(arg0);

			System.out.println("聚会的id:" + model.getPa_seq_id());

			title.setText("标题:" + model.getPa_title());

			time.setText("时间:" + model.getPa_start_time() + "--"
					+ model.getEnd_time());
			content.setText("内容:"
					+ model.getPa_comment());

			root.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					quickActionMenu(v, mList.get(position));
				}
			});

			return root;

		}
	}

	/**
	 * 启动快速链接
	 * 
	 * @param v
	 */
	private void quickActionMenu(View v, final PartyModel model) {

		ActionItem openAction = new ActionItem();
		openAction.setTitle("评论");
		openAction.setIcon(getResources().getDrawable(R.drawable.pl_img));
		ActionItem callAction = new ActionItem();
		callAction.setTitle("参加");
		callAction.setIcon(getResources().getDrawable(R.drawable.cj_img));
		ActionItem smsAction = new ActionItem();
		smsAction.setTitle("详情");
		smsAction.setIcon(getResources().getDrawable(R.drawable.in_img));

		final QuickAction mQuickAction = new QuickAction(this);
		mQuickAction.addActionItem(openAction);
		mQuickAction.addActionItem(callAction);
		mQuickAction.addActionItem(smsAction);
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(int pos) {
						switch (pos) {
						case 0:

							commnetLogic(model);

							break;
						case 1:

							takePartInLogic(model);

							break;
						case 2:

							checkDetailLogic(model);

							break;
						}
					}
				});
		mQuickAction.show(v);
	}

	/**
	 * 评论逻辑
	 */
	private void commnetLogic(PartyModel model) {

		myPopWindow = null;

		myPopWindow = new PopupWindow(this);

		myPopWindow.setFocusable(true);
		myPopWindow.setOutsideTouchable(true);
		myPopWindow.setTouchable(true);

		centerX = layout_manager_paries_father_outter_layout.getWidth() / 2;

		centerY = layout_manager_paries_father_outter_layout.getHeight() / 2;

		System.out.println("centerX:" + centerX);
		System.out.println("centerY:" + centerY);

		LayoutInflater inlater = this.getLayoutInflater();

		View root = inlater
				.inflate(R.layout.layout_comment_party_content, null);

		myPopWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.special_layout_background));

		myPopWindow.setWidth(layout_manager_paries_father_outter_layout
				.getWidth() - 20);
		myPopWindow.setHeight(layout_manager_paries_father_outter_layout
				.getHeight() - 20);

		myPopWindow.setAnimationStyle(R.style.MyPopWindow);

		myPopWindow.setContentView(root);

		myPopWindow.showAtLocation(layout_manager_paries_father_outter_layout,
				Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

		initCommentPopupWindowComponents(root, model);

	}

	/**
	 * 参加聚会逻辑
	 */
	private void takePartInLogic(PartyModel model) {
		System.out.println("参加聚会...");
		TakePartInPartyTask task = new TakePartInPartyTask();
		task.execute(arr[2], model.getPa_seq_id());

	}

	/**
	 * 查看细节逻辑
	 */
	private void checkDetailLogic(final PartyModel model) {

		myPopWindow = null;

		myPopWindow = new PopupWindow(this);

		myPopWindow.setFocusable(true);
		myPopWindow.setOutsideTouchable(true);
		myPopWindow.setTouchable(true);

		centerX = layout_manager_paries_father_outter_layout.getWidth() / 2;

		centerY = layout_manager_paries_father_outter_layout.getHeight() / 2;

		System.out.println("centerX:" + centerX);
		System.out.println("centerY:" + centerY);

		LayoutInflater inlater = this.getLayoutInflater();

		View root = inlater.inflate(R.layout.layout_party_detail_content, null);

		myPopWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.special_layout_background));

		myPopWindow.setWidth(layout_manager_paries_father_outter_layout
				.getWidth() - 20);
		myPopWindow.setHeight(layout_manager_paries_father_outter_layout
				.getHeight() - 20);

		myPopWindow.setAnimationStyle(R.style.MyPopWindow);

		myPopWindow.setContentView(root);

		myPopWindow.showAtLocation(layout_manager_paries_father_outter_layout,
				Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);

		myPopWindow.setTouchInterceptor(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				// TODO Auto-generated method stub

				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {

					myPopWindow.dismiss();
					return true;
				}
				return false;
			}
		});

		initDetailPopupWindowComponents(root, model);

	}

	/**
	 * 初始化信息弹出框
	 * 
	 * @param root
	 * @param model
	 */
	private void initDetailPopupWindowComponents(View root,
			final PartyModel model) {

		final ImageView closeButtonImageView = (ImageView) root
				.findViewById(R.id.close_button_cross_imageview);

		closeButtonImageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				MyAnimationUtils.closeLayout(closeButtonImageView,
						PariesCreateByMeFrame.this, myPopWindow);

			}
		});

		final EditText party_input_title = (EditText) root
				.findViewById(R.id.party_input_title);

		final EditText party_input_content = (EditText) root
				.findViewById(R.id.party_input_content);

		final TextView party_pure_show_time_textview = (TextView) root
				.findViewById(R.id.party_pure_show_time_textview);

		party_input_title.setText(model.getPa_title());

		party_input_content.setText(model.getPa_comment());

		party_pure_show_time_textview.setText("[" + model.getPa_start_time()
				+ "--" + model.getEnd_time() + "]");

	}

	/**
	 * 初始化评论弹出框控件
	 * 
	 * @param root
	 */
	private void initCommentPopupWindowComponents(View root,
			final PartyModel model) {
		final EditText party_input_title = (EditText) root
				.findViewById(R.id.party_input_title);

		final EditText party_input_content = (EditText) root
				.findViewById(R.id.party_input_content);

		final ImageView closeButtonImageView = (ImageView) root
				.findViewById(R.id.close_button_cross_imageview);

		party_input_title.setText(model.getPa_title());

		closeButtonImageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				MyAnimationUtils.closeLayout(closeButtonImageView,
						PariesCreateByMeFrame.this, myPopWindow);

			}
		});

		final Button yesButton = (Button) root
				.findViewById(R.id.comment_yes_button);

		yesButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				CommentTask task = new CommentTask();
				task.execute(arr[2], model.getPa_seq_id(), party_input_content
						.getText().toString(), GenerateTime.getCurrentTime());

			}
		});

		final Button noButton = (Button) root
				.findViewById(R.id.comment_no_button);

		noButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				System.out.println("关闭");
				myPopWindow.dismiss();

			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (myPopWindow != null) {
				if (myPopWindow.isShowing()) {

					myPopWindow.dismiss();

					return true;
				}
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 评论异步任务
	 * 
	 * @author cesc
	 * 
	 */
	private class CommentTask extends AsyncTask<String, String, String> {

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			System.out.println("评论的返回结果是：" + result);
			ProgressDialogUtility.cancelDialog();

			if (result.equals("comment_successed")) {

				ToastUtility.showToast(PariesCreateByMeFrame.this, "评论成功");

				myPopWindow.dismiss();

			} else if (result.equals("comment_failed")) {

				ToastUtility.showToast(PariesCreateByMeFrame.this,
						"评论失败,服务器有点不给力了");

			} else {

				ToastUtility.showToast(PariesCreateByMeFrame.this,
						"评论失败,亲你的网开了吗？");
			}

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			ProgressDialogUtility.showDialog(PariesCreateByMeFrame.this,
					"评论中..");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub

			String rlt = "nodatas";
			rlt = WebRequestContext.createInstance(
					WebRequestContext.TYPE_COMMENT_PARTY)
					.getWebRequestRlt(arg0);

			return rlt;
		}

	}

	/**
	 * 参加聚会的实现类
	 * 
	 * @author cesc
	 * 
	 */
	private class TakePartInPartyTask extends AsyncTask<String, String, String> {

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			if (result.equals("take_part_in_party_successed")) {

				ToastUtility.showToast(PariesCreateByMeFrame.this,
						"加入聚会成功，等待参加聚会吧!");

			} else {

				ToastUtility.showToast(PariesCreateByMeFrame.this, "加入聚会失败");

			}

			ProgressDialogUtility.cancelDialog();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			ProgressDialogUtility.showDialog(PariesCreateByMeFrame.this,
					"加入聚会中..");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String rlt = "";

			rlt = WebRequestContext.createInstance(
					WebRequestContext.TYPE_TAKE_PART_IN_PARTY)
					.getWebRequestRlt(params);
			System.out.println("加入聚会的请求值是:" + rlt);
			return rlt;
		}

	}

}
